<?php

namespace Lib;

use Common;
use Sdk\lib\Core;

class Pay {

	const Status_Default = -1;//新单
	const Status_Paid = 1;//已付款

	// SDK/Client 端无法之前创建真实的支付请求，将跳转到开发者模式
	public static function CreatePayUrl($params) {
		$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . Common::getURI('/system/action/pay');
		$vars = $params['vars'] ?? [];
		$orderid = 't' . date('Ymd') . Common::random(10);
		$query = array(
			'debugUrl' => $url,
			'appPath' => PLUGIN_ID . '.' . VER_ID,
			'func' => $params['func'],
		);
		if (isset($params['func']['create'])) {
			$query['params']['create'] = array(
				$vars,
				'{method}',
				$orderid,
			);
		}
		if (isset($params['func']['notify'])) {
			$query['params']['notify'] = array(
				$vars,
				$orderid,
				self::Status_Paid,
			);
		}
		// 假数据模拟入库，暂存 Redis
		Common::memory('set', 'order_' . $orderid, array(
			'payid' => time(),
			'orderid' => $orderid,
			'amount' => $params['amount'],
			'related_type' => $params['type'],
			'related_id' => $params['id'],
			'pay_method' => 1,
			'pay_data' => array(),
			'status' => 1,
			'createtime' => time(),
			'updatetime' => time(),
		), 86400);
		return WitApiURL . '/app_pay?d=' . rawurlencode(base64_encode(json_encode($query)));
	}

	// SDK/Client 端无法获取线上的订单数据，直接返回假数据
	public static function GetByOrderId($orderid) {
		return Common::memory('get', 'order_' . $orderid);
	}

}